package com.design.movieticket.login.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.design.movieticket.entity.Role;
import com.design.movieticket.entity.User;
import com.design.movieticket.entity.UserRole;
import com.design.movieticket.login.entity.LoginUser;
import com.design.movieticket.mapper.RoleMapper;
import com.design.movieticket.mapper.UserMapper;
import com.design.movieticket.mapper.UserRoleMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        System.out.println("username:" + username);
        wrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(wrapper);
        if (user == null){
            //异常信息捕获
            throw new RuntimeException("用户不存在或密码错误");
        }
        //授权
//        List<String> permissions = new ArrayList<>(Arrays.asList("test","admin"));

        LambdaQueryWrapper<UserRole> wrapperUserRole = new LambdaQueryWrapper<>();
        wrapperUserRole.eq(UserRole::getUserId,user.getId());
        UserRole userRole = userRoleMapper.selectOne(wrapperUserRole);
        long RoleId = userRole.getRoleId();

        LambdaQueryWrapper<Role> wrapperRole = new LambdaQueryWrapper<>();
        wrapperRole.eq(Role::getId,RoleId);
        Role role = roleMapper.selectOne(wrapperRole);
        List<String> permissions = Arrays.asList(role.getRoleCode());

        System.out.println("loginUser是:" + new LoginUser(user,permissions));

        //封装成UserDetails返回
        return new LoginUser(user,permissions);

    }



}
